package com.weizhong.update.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpTool {
	private static final String CHARSET = HTTP.UTF_8;
	private static final String TAG="HttpTool";
	
	/**
	 * 获得一个线程安全的httpclient
	 * 
	 * @return
	 */
	public static synchronized HttpClient getHttpClient() {
		HttpClient httpClient = null;
		if (null == httpClient) {
			try {
				HttpParams params = new BasicHttpParams();
				// 设置一些基本参数
				HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
				HttpProtocolParams.setContentCharset(params, CHARSET);
				HttpProtocolParams.setUseExpectContinue(params, true);
				HttpProtocolParams
						.setUserAgent(
								params,
								"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
										+ "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
				// 超时设置
				/* 从连接池中取连接的超时时间 */
				ConnManagerParams.setTimeout(params, 10000);
				/* 连接超时 这就是该socket连接的超时时间，此处设置为2秒 */
				HttpConnectionParams.setConnectionTimeout(params, 20000);
				/* 请求超时 这定义了Socket读数据的超时时间，即从服务器获取响应数据需要等待的时间，此处设置为4秒。 */
				HttpConnectionParams.setSoTimeout(params, 40000);

				// 设置我们的HttpClient支持HTTP和HTTPS两种模式
				SchemeRegistry schReg = new SchemeRegistry();
				schReg.register(new Scheme("http", PlainSocketFactory
						.getSocketFactory(), 80));
				schReg.register(new Scheme("https", SSLSocketFactory
						.getSocketFactory(), 443));

				// 使用线程安全的连接管理来创建HttpClient
				ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
						params, schReg);
				httpClient = new DefaultHttpClient(conMgr, params);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return httpClient;
	}

	/**
	 * 发送httppost请求
	 * 
	 * @param url
	 */
	public static String httpPostRequest(String url,NameValuePair...  params){
		 HttpClient client;
		try {
			 Logger.i(TAG, "httpPostRequest url:"+url);
            // 编码参数
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            // 请求参数
            for (NameValuePair p : params) {
                formparams.add(p);
            }
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams,
                    CHARSET);
            // 创建POST请求
            HttpPost request = new HttpPost(url);
            request.setEntity(entity);
            // 发送请求
            client = getHttpClient();
            HttpResponse response = client.execute(request);
            if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
//                throw new RuntimeException("请求失败");
            	return null;
            }
            HttpEntity resEntity =  response.getEntity();
            return (resEntity == null) ? null : EntityUtils.toString(resEntity, CHARSET);
        } catch (UnsupportedEncodingException e) {
        	e.printStackTrace();
            Logger.w(TAG, e.getMessage());
            return null;
        } catch (ClientProtocolException e) {
        	e.printStackTrace();
            Log.w(TAG, e.getMessage());
            return null;
        } catch (IOException e) {
//            throw new RuntimeException("连接失败", e);
        	e.printStackTrace();
        	Logger.e(TAG, "连接失败");
        	return null;
        }catch(Exception e){
        	e.printStackTrace();
        	return null;
        }
		finally{
		}
	}

	/**
	 * 发送httpget请求
	 * 
	 * @param url
	 */
	public static String httpGetRequest(String url,HttpParams params) {
		
		String strResult;
		// HttpGet连接对象
	     HttpGet httpRequest = new HttpGet(url);
	     httpRequest.setParams(params);
	     // 取得HttpClient对象
	     HttpClient httpclient = getHttpClient();
	  // 请求HttpClient，取得HttpResponse
	     HttpResponse httpResponse;
		try {
			httpResponse = httpclient.execute(httpRequest);
			// 请求成功
		     if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
		      // 取得返回的字符串
		      strResult = EntityUtils.toString(httpResponse
		        .getEntity());
		      return strResult;
		     }
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	     return null;
	}
}
